#include "app_mqtt.h"
/*
 * @Author: jack_yang98 1246900429@qq.com
 * @Date: 2024-08-03 21:43:32
 * @LastEditors: jack_yang98 1246900429@qq.com
 * @LastEditTime: 2024-08-04 01:25:21
 * @FilePath: /gateway/app/app_mqtt copy.h
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <MQTTClient.h>
#include <assert.h>
#include <stdlib.h>
#include "thirdparty/log/log.h"

#define CLIENT_ID "jack-89543847369a"
#define PULL_TOPIC "TEST_PUSH"
#define PUSH_TOPIC "TEST_PUSH"

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_deliveryToken token;
static int (*recv_callback)(char *, int);

/**
 * @description: 连接丢失时的回调函数
 * @param {void} *context
 * @param {char} *cause
 * @return {*}
 */
void App_mqtt_connectionLostCallback(void *context, char *cause)
{
    assert(context == NULL);
    log_error("连接丢失 : %s", cause);
    exit(EXIT_FAILURE);
}

/**
 * @description: 信息到达的回调函数
 * @param {void} *context
 * @param {char} *topicName
 * @param {int} topicLen
 * @param {MQTTClient_message} *message
 * @return {*}
 */
int App_mqtt_messageArrivedCallback(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    assert(context == NULL);
    log_trace("Message arrived\n\ttopic: %.*s\n\tpayload: %.*s", topicLen, topicName, (int)message->payloadlen, (char *)message->payload);

    int rc = recv_callback((char *)message->payload, message->payloadlen);

    return rc == 0 ? 1 : 0;
}

/**
 * @description: 数据发送完成的回调
 * @param {void} *context
 * @param {MQTTClient_deliveryToken} dt
 * @return {*}
 */
void App_mqtt_deliveryCompleteCallback(void *context, MQTTClient_deliveryToken dt)
{
    assert(context == NULL);
    log_trace("数据到达 %d ", dt);
}

int App_mqtt_init()
{
    // 初始化客户端
    int rc = MQTTClient_create(&client, MQTT_SERVER, CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_create 创建失败,rc = %d", rc);
        goto CREATE_FAIL;
    }

    // 设置回调函数
    rc = MQTTClient_setCallbacks(client, NULL, App_mqtt_connectionLostCallback,
                                 App_mqtt_messageArrivedCallback,
                                 App_mqtt_deliveryCompleteCallback);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_setCallbacks 创建回调函数失败 rc = %d", rc);
        goto CONNECT_FAIL;
    }

    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    rc = MQTTClient_connect(client, &conn_opts);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_connect 连接失败 rc = %d", rc);
        goto CONNECT_FAIL;
    }
    // 订阅主题
    rc = MQTTClient_subscribe(client, PULL_TOPIC, 0);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_subscribe 订阅失败 rc = %d", rc);
        goto DISCONNECT_EXIT;
    }

    log_info("MQTTClient_connect 连接成功");
    return 0;
// 断开连接
DISCONNECT_EXIT:
    MQTTClient_disconnect(client, 1000); // 断开连接
// 连接失败
CONNECT_FAIL:
    MQTTClient_destroy(&client);
// 创建失败
CREATE_FAIL:
    return -1;
}

void App_mqtt_reisterRecvCallback(int (*callback)(char *, int))
{
    recv_callback = callback;
}

int App_mqtt_send(char *json_str, int len)
{
    MQTTClient_message message = MQTTClient_message_initializer;
    message.payload = json_str;
    message.payloadlen = len;
    message.qos = 0;
    message.retained = 0;
    int rc = MQTTClient_publishMessage(client, PUSH_TOPIC, &message, &token);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_publishMessage 发送失败 rc = %d", rc);
        return -1;
    }
    log_trace("MQTTClient_publishMessage 发送成功 token = %d",token);
    return 0;
}

int App_mqtt_close()
{
    int rc;
    rc = MQTTClient_disconnect(client, 1000); // 断开连接
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_disconnect 断开连接失败 rc = %d", rc);
        return -1;
    }
    MQTTClient_destroy(&client);
    log_trace("MQTTClient_destroy 销毁成功");
    return 0;
}
